package Models;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import db.JPA;

public class User {
    private static JPA jpa = new JPA();
    private String username;
    private String password;

    /**
     * @param username
     * @param password
     * @param role
     */
    public User(String username, String password) {
	this.setUsername(username);
	this.setPassword(password);
    }

    /**
     * @param username
     * @param password
     * @return
     */
    public static boolean authenticate(String username, String password) {
	try {
	    User u = getUserByUsername(username);

	    if (password.equals(u.getPassword())) {
		Session.setCurrentUser(u);
		return true;
	    }
	} catch (userNotFound ex) {
	    return false;
	}

	return false;
    }

    /**
     * @return
     */
    public boolean save() {
	try {
	    User.getUserByUsername(username);
	    return false;
	} catch (userNotFound e1) {
	    String[] columns = { "id_usuario", "contrasenia" };

	    PreparedStatement stm = jpa.newRecord("liliana.usuario", columns);

	    try {
		stm.setString(1, username);
		stm.setString(2, password);
	    } catch (SQLException e) {
		e.printStackTrace();
		return false;
	    }

	    jpa.create(stm);// inserta en la base de datos
	    return true;
	}
    }

    /**
     * @return
     */
    public boolean destroy() {
		try {
		    String[] columns = {"id_usuario"};
		    String[] values = {this.getUsername()};
		    jpa.destroy("usuario",columns, values);
		    return true;
		} catch (SQLException e) {
		    return false;
		}
	}

    /**
     * @param username
     * @return
     * @throws userNotFound
     */
    public static User getUserByUsername(String username) throws userNotFound {
	ResultSet rs = null;
	User u = null;

	rs = jpa.getByField("usuario", "id_usuario", username);

	try {
	    if (rs.next()) {
		u = new User(rs.getString(1), rs.getString(2));
	    } else {
		throw new userNotFound();
	    }
	} catch (SQLException e) {
	    e.printStackTrace();
	}

	return u;
    }

    public String getUsername() {
	return username;
    }

    public void setUsername(String username) {
	this.username = username;
    }

    public String getPassword() {
	return password;
    }

    public void setPassword(String password) {
	this.password = password;
    }

}
